package com.hbnu.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbnu.system.config.BaseException;
import com.hbnu.system.constant.AuthorTypeConstants;
import com.hbnu.system.mapper.TranprojectauthorMapper;
import com.hbnu.system.model.entity.Tranproject_registration;
import com.hbnu.system.model.entity.Tranprojectauthor;
import com.hbnu.system.model.entity.User;
import com.hbnu.system.service.IProjectQualificationService;
import com.hbnu.system.service.ITranproject_registrationService;
import com.hbnu.system.service.IUserService;
import com.hbnu.system.service.TranprojectauthorService;
import com.hbnu.system.utils.CheckRoleUtil;
import com.hbnu.system.utils.IdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 横向项目作者服务实现类
 */
@Service
public class TranprojectauthorServiceImpl extends ServiceImpl<TranprojectauthorMapper, Tranprojectauthor> implements TranprojectauthorService {

    @Autowired
    private ITranproject_registrationService iTranprojectRegistrationService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private CheckRoleUtil checkRoleUtil;

    @Autowired
    private IProjectQualificationService iProjectQualificationService;

    private static final List<String> AUTHOR_TYPE_ORDER = Arrays.asList(
            "1", "2", "3", "4", "5", "6","7", "8", "9", "10"
    );

    // 用于保留两位小数的格式化器
    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.00");


    /**
     * 添加横向项目作者
     * @param tranprojectauthor 横向项目作者信息
     * @return 添加操作是否成功
     */
    @Transactional
    @Override
    public boolean addtranprojectAuthor(Tranprojectauthor tranprojectauthor) {
        // 不使用前端传过来的ID，生成新ID
        tranprojectauthor.setTranprojecauthorid(null);

        // 检查项目是否存在并校验权限
        Tranproject_registration project = iTranprojectRegistrationService.getOne(
                Wrappers.lambdaQuery(Tranproject_registration.class)
                        .eq(Tranproject_registration::getTRegistrationID, tranprojectauthor.getTregistrationid())
        );
        checkRoleUtil.checkPermissionProject(project.getProjectState());

        //如果是校外作者或者学生，为其生成工号
        if (tranprojectauthor.getAuthorType().equals(AuthorTypeConstants.OUT_SCHOOL_AUTHOR)
                ||tranprojectauthor.getAuthorType().equals(AuthorTypeConstants.STUDENT)) {
            tranprojectauthor.setUserAccount(IdGenerator.generateId());
        }

        // 检查工号是否为空
        if (StrUtil.isEmpty(tranprojectauthor.getUserAccount())) {
            throw new BaseException("请输入工号");
        }


        // 检查是否重复添加
        Tranprojectauthor existingAuthor = getOne(
                Wrappers.lambdaQuery(Tranprojectauthor.class)
                        .eq(Tranprojectauthor::getTregistrationid, tranprojectauthor.getTregistrationid())
                        .eq(Tranprojectauthor::getUserAccount, tranprojectauthor.getUserAccount())
        );
        if (Objects.nonNull(existingAuthor)) {
            throw new BaseException("不可重复添加");
        }

        // 检查排名是否为空
        if (StrUtil.isBlank(tranprojectauthor.getRanking())) {
            throw new BaseException("请输入排名");
        }

        // 检查考核系数
        double newAssessment;
        try {
            newAssessment = Double.parseDouble(tranprojectauthor.getAssessment());
        } catch (NumberFormatException e) {
            throw new BaseException("考核系数格式不正确");
        }
        if (newAssessment < 0 || newAssessment > 100) {
            throw new BaseException("考核系数应在 0 到 100 之间");
        }

        String Pscore = "0.00";


        Tranproject_registration tranproject_registration=iTranprojectRegistrationService.getTranproject(tranprojectauthor.getTregistrationid());
        if(tranproject_registration != null){
            int finalValue = (int) tranproject_registration.getScore();
            // 计算并保留两位小数
            double pscore = finalValue * newAssessment / 100.0;
            Pscore = DECIMAL_FORMAT.format(pscore);
        }

        // 计算考核系数总和（只计算已填写考核系数的作者）
        List<Tranprojectauthor> authors = list(
                Wrappers.lambdaQuery(Tranprojectauthor.class)
                        .eq(Tranprojectauthor::getTregistrationid, tranprojectauthor.getTregistrationid())
        );
        
        // 只计算已填写考核系数的作者
        Double totalAssessment = authors.stream()
                .filter(author -> !StrUtil.isBlank(author.getAssessment()))
                .mapToDouble(author -> Double.parseDouble(author.getAssessment()))
                .sum();
        
        // 检查已填写考核系数的总和是否超过100
        if (totalAssessment + newAssessment > 100) {
            throw new BaseException("已填写作者考核系数总和大于100!");
        }

        tranprojectauthor.setPscore(Pscore);

        // 插入作者信息
        boolean insertResult = save(tranprojectauthor);

        // 维护 ProjectMembers 字段
        updateProjectMembers(project, tranprojectauthor);

        return insertResult;
    }

    /**
     * 删除横向项目作者
     * @param id 作者ID
     * @return 删除操作是否成功
     */
    @Override
    public boolean deletetranprojectAuthor(String id) {
        Tranprojectauthor tranprojectauthor = getOne(
                Wrappers.lambdaQuery(Tranprojectauthor.class)
                        .eq(Tranprojectauthor::getTranprojecauthorid, id)
        );
        if (Objects.isNull(tranprojectauthor)) {
            throw new BaseException("不存在关联作者");
        }

        Tranproject_registration project = iTranprojectRegistrationService.getOne(
                Wrappers.lambdaQuery(Tranproject_registration.class)
                        .eq(Tranproject_registration::getTRegistrationID, tranprojectauthor.getTregistrationid())
        );
        checkRoleUtil.checkPermissionProject(project.getProjectState());

        boolean deleteResult = removeById(tranprojectauthor.getTranprojecauthorid());

        // 维护 ProjectMembers 字段
        updateProjectMembers(project, tranprojectauthor);

        return deleteResult;
    }

    /**
     * 修改横向项目作者
     * @param tranprojectauthor 横向项目作者信息
     * @return 修改操作是否成功
     */
    @Override
    public boolean updatetranprojectAuthor(Tranprojectauthor tranprojectauthor) {
        Tranproject_registration project = iTranprojectRegistrationService.getOne(
                Wrappers.lambdaQuery(Tranproject_registration.class)
                        .eq(Tranproject_registration::getTRegistrationID, tranprojectauthor.getTregistrationid())
        );
        checkRoleUtil.checkPermissionProject(project.getProjectState());

        // 检查考核系数
        double newAssessment;
        try {
            String assessment = tranprojectauthor.getAssessment();
            // 如果考核系数为null或空，默认为0
            if (assessment == null || assessment.trim().isEmpty()) {
                newAssessment = 0.0;
            } else {
                newAssessment = Double.parseDouble(assessment);
            }
        } catch (NumberFormatException e) {
            throw new BaseException("考核系数格式不正确");
        }
        if (newAssessment < 0 || newAssessment > 100) {
            throw new BaseException("考核系数应在 0 到 100 之间");
        }

        String Pscore = "0.00";

        Tranproject_registration tranproject_registration=iTranprojectRegistrationService.getTranproject(tranprojectauthor.getTregistrationid());
        if(tranproject_registration != null){
            int finalValue = (int) tranproject_registration.getScore();
            // 计算并保留两位小数
            double pscore = finalValue * newAssessment / 100.0;
            Pscore = DECIMAL_FORMAT.format(pscore);
        }

        // 计算考核系数总和（排除当前修改作者，只计算已填写考核系数的作者）
        List<Tranprojectauthor> authors = list(
                Wrappers.lambdaQuery(Tranprojectauthor.class)
                        .eq(Tranprojectauthor::getTregistrationid, tranprojectauthor.getTregistrationid())
                        .ne(Tranprojectauthor::getTranprojecauthorid, tranprojectauthor.getTranprojecauthorid())
        );
        
        // 只计算已填写考核系数的作者
        Double totalAssessment = authors.stream()
                .filter(author -> !StrUtil.isBlank(author.getAssessment()))
                .mapToDouble(author -> Double.parseDouble(author.getAssessment()))
                .sum();
        
        // 检查已填写考核系数的总和是否超过100
        if (totalAssessment + newAssessment > 100) {
            throw new BaseException("已填写作者考核系数总和大于100!");
        }

        tranprojectauthor.setPscore(Pscore);

        boolean updateResult = updateById(tranprojectauthor);

        // 维护 ProjectMembers 字段
        updateProjectMembers(project, tranprojectauthor);

        return updateResult;
    }

    /**
     * 根据横向项目ID获取作者列表
     * @param id 横向项目ID
     * @return 作者列表
     */
    @Override
    public List<Tranprojectauthor> tranprojectauthor(String id) {
        Tranproject_registration project = iTranprojectRegistrationService.getOne(
                Wrappers.lambdaQuery(Tranproject_registration.class)
                        .eq(Tranproject_registration::getTRegistrationID, id)
        );

        // 清空原有字段
        project.setProjectMembers(null);
        iTranprojectRegistrationService.updateById(project);

        List<Tranprojectauthor> authorList = list(
                Wrappers.lambdaQuery(Tranprojectauthor.class)
                        .eq(Tranprojectauthor::getTregistrationid, id)
        );
        authorList.sort(Comparator.comparingInt(author -> Integer.parseInt(author.getRanking())));

        // 获取项目负责人姓名
        String headName = project.getHeadName();

        // 获取所有作者姓名，但跳过与项目负责人姓名相同的成员
        List<String> userNames = authorList.stream()
                .filter(author -> headName == null || !headName.equals(author.getName()))
                .map(Tranprojectauthor::getName)
                .collect(Collectors.toList());

        // 更新 ProjectMembers 字段
        String projectMembers = String.join(",", userNames);
        project.setProjectMembers(projectMembers);
        iTranprojectRegistrationService.updateById(project);
        return authorList;
    }



    /**
     * 维护 ProjectMembers 字段
     * @param project 横向项目对象
     * @param tranprojectauthor 当前操作的作者
     */
    private void updateProjectMembers(Tranproject_registration project, Tranprojectauthor tranprojectauthor) {
        // 清空原有字段
        project.setProjectMembers(null);
        iTranprojectRegistrationService.updateById(project);

        // 获取所有作者
        List<Tranprojectauthor> allAuthors = list(
                Wrappers.lambdaQuery(Tranprojectauthor.class)
                        .eq(Tranprojectauthor::getTregistrationid, tranprojectauthor.getTregistrationid())
        );
        allAuthors.sort(Comparator.comparingInt(author -> Integer.parseInt(author.getRanking())));

        // 获取项目负责人姓名
        String headName = project.getHeadName();
        
        // 获取所有作者姓名，但跳过与项目负责人姓名相同的成员
        List<String> userNames = allAuthors.stream()
                .filter(author -> headName == null || !headName.equals(author.getName()))
                .map(Tranprojectauthor::getName)
                .collect(Collectors.toList());

        // 更新 ProjectMembers 字段
        String projectMembers = String.join(",", userNames);
        project.setProjectMembers(projectMembers);
        iTranprojectRegistrationService.updateById(project);
    }
}